﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CoolCode;
using CoolCode.Linq;
using CoolCode.Web;
using CoolCode.Web.Mvc;
using XNoteBook.Entities;
using XNoteBook.Services;
using XNoteBook.Models;
using System.Reflection;

namespace XNoteBook.UI.Controllers
{
	public class TableController : CoolCode.Web.Mvc.ControllerBase
	{
		private IPostService _PostService;
		public IPostService PostService
		{
			get
			{
				if (_PostService == null)
				{
					_PostService = Digger.Dig<IPostService>();
				}
				return _PostService;
			}
		}

		//
		// GET: /Table/

		public ActionResult Index()
		{
			Title = "数据表管理";
			List<Type> tableTypes = new List<Type>();
			foreach (Assembly assem in AppDomain.CurrentDomain.GetAssemblies())
			{     //反射当前程序集的信息   
				tableTypes.AddRange(  assem.GetTypes().Where(c => c.FullName.Contains("XNoteBook.Entities"))) ; 
			}  
			return View(tableTypes .Select(c=> c.Name ));
		}

		//
		// GET: /Table/Details/5

		public ActionResult Details(string id)
		{
			Title = id + "数据列表";
			//var q = this.PostService.QueryNode( QueryBuilder.Create<NodeModel>());
			var provider = CoolCode.Data.DataContextProxy.Instance.Provide();
			Type tableType =null ;
			foreach (Assembly assem in AppDomain.CurrentDomain.GetAssemblies())    
			{     //反射当前程序集的信息   
				tableType = assem.GetType("XNoteBook.Entities." + id);
				if (tableType != null) 
					break;
			}  
			//var tableType =  Type.GetType("XNoteBook.Entities." + id); 
			var createRepository = provider.GetType().GetMethod("CreateRepository");
			createRepository = createRepository.MakeGenericMethod(tableType);
			var model = createRepository.Invoke(provider, null);//, 

			return View(model);
		}

		//
		// GET: /Table/Create

		public ActionResult Create()
		{
			return View();
		}

		//
		// POST: /Table/Create

		[HttpPost]
		public ActionResult Create(FormCollection collection)
		{
			try
			{
				// TODO: Add insert logic here

				return RedirectToAction("Index");
			}
			catch
			{
				return View();
			}
		}

		//
		// GET: /Table/Edit/5

		public ActionResult Edit(int id)
		{
			return View();
		}

		//
		// POST: /Table/Edit/5

		[HttpPost]
		public ActionResult Edit(int id, FormCollection collection)
		{
			try
			{
				// TODO: Add update logic here

				return RedirectToAction("Index");
			}
			catch
			{
				return View();
			}
		}

		//
		// GET: /Table/Delete/5

		public ActionResult Delete(int id)
		{
			return View();
		}

		//
		// POST: /Table/Delete/5

		[HttpPost]
		public ActionResult Delete(int id, FormCollection collection)
		{
			try
			{
				// TODO: Add delete logic here

				return RedirectToAction("Index");
			}
			catch
			{
				return View();
			}
		}
	}
}
